import React, { useState, useMemo, useEffect } from 'react';
import { Card, Select, Typography, Empty, Spin, message } from 'antd';
import { VideoCameraOutlined } from '@ant-design/icons';
import { useWebSocket } from '../../contexts/WebSocketContext';
import axios from 'axios';

const { Title } = Typography;
const { Option } = Select;

const LiveCameraFeed: React.FC = () => {
    const { devices, isConnected } = useWebSocket();
    const [selectedDeviceId, setSelectedDeviceId] = useState<string | null>(null);
    const [videoSrc, setVideoSrc] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);

    const devicesWithCamera = useMemo(() => {
        return devices.filter(device => device.camera_service_name);
    }, [devices]);

    const handleDeviceChange = (value: string) => {
        setSelectedDeviceId(value);
    };

    // Automatically select the first available camera if none is selected
    useEffect(() => {
        if (!selectedDeviceId && devicesWithCamera.length > 0) {
            setSelectedDeviceId(devicesWithCamera[0].device_id);
        }
    }, [devicesWithCamera, selectedDeviceId]);

    // Fetch the authenticated video stream URL when selectedDeviceId changes
    useEffect(() => {
        const fetchVideoStreamUrl = async () => {
            if (!selectedDeviceId) {
                setVideoSrc(null);
                return;
            }

            setIsLoading(true);
            setVideoSrc(null);
            const token = localStorage.getItem('adminAuthToken');
            if (!token) {
                message.error("管理员未登录，无法加载视频。");
                setIsLoading(false);
                return;
            }

            try {
                // Step 1: Get the authenticated URL from our Django backend
                const response = await axios.get(
                    `/api/admin/devices/${selectedDeviceId}/stream_url/`,
                    {
                        headers: { Authorization: `Token ${token}` },
                    }
                );
                
                // Step 2: Set the URL (which points directly to the camera service) to the img src
                setVideoSrc(response.data.url);

            } catch (error) {
                console.error("获取视频流URL失败:", error);
                message.error("获取视频流授权失败，请检查后端服务。");
                setVideoSrc(null);
            } finally {
                // We set loading to false here, the browser will handle loading the image
                setIsLoading(false);
            }
        };

        fetchVideoStreamUrl();

    }, [selectedDeviceId]);

    return (
        <Card
            title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <VideoCameraOutlined style={{ marginRight: 8, fontSize: '20px' }} />
                    <Title level={5} style={{ margin: 0 }}>实时视频监控</Title>
                </div>
            }
            extra={
                <Select
                    style={{ width: 200 }}
                    placeholder="选择摄像头"
                    onChange={handleDeviceChange}
                    loading={!isConnected && devices.length === 0}
                    disabled={!isConnected || devicesWithCamera.length === 0}
                    value={selectedDeviceId}
                >
                    {devicesWithCamera.map(device => (
                        <Option key={device.device_id} value={device.device_id}>
                            {device.name} ({device.location})
                        </Option>
                    ))}
                </Select>
            }
        >
            <div style={{ height: 480, display: 'flex', justifyContent: 'center', alignItems: 'center', background: '#000', borderRadius: '8px', overflow: 'hidden' }}>
                {(() => {
                    if (isLoading) {
                        return <Spin tip="获取授权中..." />;
                    }
                    if (videoSrc) {
                        return (
                            <img
                                src={videoSrc}
                                alt="Live camera feed"
                                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                                onLoad={() => console.log("视频流加载成功！")}
                                onError={() => {
                                    message.error("视频流加载失败。请检查摄像头服务是否在线，以及网络配置是否正确。");
                                    setVideoSrc(null);
                                }}
                            />
                        );
                    }
                    if (!isConnected && devices.length === 0) {
                        return <Spin tip="等待连接监控服务..." />;
                    }
                    if (devicesWithCamera.length === 0) {
                        return <Empty description="没有发现已关联摄像头的设备" />;
                    }
                    if (!selectedDeviceId) {
                        return <Empty description="请从右上角选择一个摄像头以开始监控" />;
                    }
                    // Fallback empty state
                    return <Empty description="视频加载失败或无信号" />;
                })()}
            </div>
        </Card>
    );
};

export default LiveCameraFeed;